<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MailingQueClass
 *
 * @author juwking
 */
class MailingQueClass {
    const messagePath="../messages/";
    private $message;
    private $targets;

    function __construct($message) {
        $this->message = $message;
    }

    function updateTarget($target) {
        $target = str_replace("target:", "", $target);
        if (!isset($this->targets[$target]))
            $this->targets[$target] = $target;
        else
            unset($this->targets[$target]);
    }

    public function getTargets() {
        return $this->targets;
    }

    public function getTargetNum() {
        return count($this->targets);
    }

    public function getMessageId() {
        return $this->message->getMessageId();
    }

    public function getMessageContent() {
        return $this->readMessage(MailingPage::messagePath . $this->message->getMessagePath());
    }

    public function evaluate() {
        $clients = ClientQuery::create()->filterByClientId($this->targets)->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();
        $this->targets = $clients->getData();
    }

    private function readMessage($filename) {
        $fh = fopen($filename, 'r');
        $theData = fread($fh, filesize($filename));
        fclose($fh);
        return $theData;
    }

    public function makeQue() {
        $mailque = new Mailque();
        $mailque->setMessage($this->message);
        $mailque->setMailqueClientId($this->targets[0]);
        $mailque->setUsers($_SESSION['UserAccess']);
        $mailque->save();
        $myFile = '../mailqueData/'.$mailque->getMailqueId().'.txt';
        $fh = fopen($myFile, 'w') or die("can't open file");
        $stringData.=$this->message->getMessageId();
        $stringData.="\r\n";
        foreach ($this->targets as $key => $value) {
                $stringData.=$value['Email'];
            $stringData.="\r\n";
        }
        fwrite($fh, $stringData);
        fclose($fh);
        
    }

}

?>
